#include "surface_line.h"
#include "util.h"
#include <limits>
#include <iostream>
#include <algorithm>
using namespace std;
surface_line::surface_line(mesh& m, int face_id, float angle, float u, float v, float max_length, int max_segments) { 
    int edge_id = face_id;
    float len = 0.0f;
    for (int i = 0; i < max_segments; ++i) {
        float l = len;
        segments.push_back(make_pair(l, m.sline(u, v, angle, face_id, len)));
        if (l > max_length) break;
    }
}

uv surface_line::uv_at(float d) { 
    if (d == 0.0f) {
        const segment& seg = segments.begin()->second;
        return uv { seg.face, seg.uv1, seg.ang };
    }
    auto low = lower_bound(segments.begin(), segments.end(), d, [](const std::pair<float,segment>& a, float b) { return a.first < b; });
    if (low == segments.end()) return uv {1, {0.5, 0.5}};

    low = low - 1;
    const segment& seg = low->second;
    float ratio = (d - low->first) / seg.l;
    vec2f mid = lerp(ratio, seg.uv1,  seg.uv2);

    return uv { seg.face, mid, seg.ang };
}

uv surface_line::st_at(const mesh& coarse, const uv& uv) { }
uv surface_line::st_at(const mesh& coarse, float d) { }
